# -*- coding: utf-8 -*-
"""
Created on 03 08 下午4:55 2022 
@Author : HHQUAN
@Email : 1075960398@qq.com

"""

import numpy as np
import matplotlib.pyplot as plt

# 5,6

fid = open('/home/cl/Downloads/2020下半年/speex相关/20220518测试/speexdsp-1.2rc3/release/build/data9/mic1.pcm', 'rb')
tmp = fid.read()
fid.close()
mic = np.frombuffer(tmp, dtype=np.int16, count=-1)

fid = open('/home/cl/Downloads/2020下半年/speex相关/20220518测试/speexdsp-1.2rc3/release/build/aec.pcm', 'rb')
tmp = fid.read()
fid.close()
aec = np.frombuffer(tmp, dtype=np.int16, count=-1)

"""
ERLE : echo return loss enhancement
输入麦克/残差，只针对单讲，其值越大越好
"""
lens = 480
frames = mic.size//lens - 1
mic_e = np.zeros((frames, ), dtype=np.float32)
echo_e = np.zeros((frames, ), dtype=np.float32)
erle = np.zeros((frames, ), dtype=np.float32)
for n in range(frames):
    x1 = mic[n*lens: n*lens+lens]*1.0
    e = np.mean(x1*x1)
    x2 = aec[n*lens: n*lens+lens]*1.0
    e2 = np.mean(x2*x2)
    if n==0:
        mic_e[n], echo_e[n] = e, e2
    else:
        mic_e[n] = 0.92*mic_e[n-1] + 0.08*e
        echo_e[n] = 0.92*echo_e[n-1] + 0.08*e2
    if echo_e[n]>=100:
        erle[n] = 10*np.log10(mic_e[n]/echo_e[n])

plt.figure()
plt.subplot(212)
plt.plot(np.arange(0, erle.size)*0.01, erle)
plt.grid(True, linestyle=':', color='gray')
plt.ylim((0, 50))
plt.xlim((0, erle.size*0.01))
plt.ylabel('ERLE-single-talk')
plt.subplot(211)
plt.plot(np.arange(0, mic.size)/48000, mic, 'b')
plt.plot(np.arange(0, aec.size)/48000, aec, 'r')
plt.ylim((-32768, 32768))
plt.xlim((0, mic.size/48000.0))
plt.grid(True, linestyle=':', color='gray')
plt.savefig('data7.png')
plt.show()

